<template>
  <el-form ref="formRef" :model="password" :rules="rules" :label-width="200">
    <el-form-item label="原密码" prop="oldPassword">
      <InputPassword v-model="password.oldPassword" />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <InputPassword v-model="password.newPassword" strength />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <InputPassword v-model="password.confirmPassword" strength />
    </el-form-item>
    <el-form-item>
      <XButton title="保存" type="primary" @click="submit(formRef)" :disabled="keyLoading" />
      <XButton title="重置" type="danger" @click="reset(formRef)" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router' // 路由跳转
import { nextTick } from 'vue'

import { InputPassword } from '@/components/InputPassword'
import { updateUserPassword } from '@/api/system/user/profile'
import { SecurityApi } from '@/api/system/security' // 加密接口
import JSEncrypt from 'jsencrypt' // RSA加密库
// 复用 UserInfo 组件的退出依赖
import { useUserStore } from '@/store/modules/user'
import { useTagsViewStore } from '@/store/modules/tagsView'

defineOptions({ name: 'ResetPwd' })

// 移除国际化，直接使用中文提示
const message = useMessage()
const formRef = ref<FormInstance>()
const router = useRouter()
// 与 UserInfo 组件一致的状态管理实例
const userStore = useUserStore()
const tagsViewStore = useTagsViewStore()

// 密码表单数据
const password = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加密相关
const keyLoading = ref(false)
const publicKey = ref('')
const encryptor = new JSEncrypt()

// 表单校验（中文提示，移除国际化）
const equalToPassword = (_rule, value, callback) => {
  if (password.newPassword !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

/**
 * 获取RSA公钥
 */
const fetchPublicKey = async () => {
  if (publicKey.value) return true
  try {
    keyLoading.value = true
    const res = await SecurityApi.getPublicKey()
    publicKey.value = res.publicKey
    encryptor.setPublicKey(publicKey.value)
    return true
  } catch (error) {
    message.error('获取加密公钥失败，请重试')
    return false
  } finally {
    keyLoading.value = false
  }
}

/**
 * RSA加密密码
 */
const encryptPassword = (data: string) => {
  if (!publicKey.value) throw new Error('公钥不存在，无法加密')
  return encryptor.encrypt(data) || ''
}

/**
 * 密码修改成功后：完全复用 UserInfo 的退出逻辑
 */
const handleLogoutAfterReset = async () => {
  try {
    // 1. 调用后端退出接口（与 UserInfo 一致）
    await userStore.loginOut()
    // 2. 清除标签页缓存（与 UserInfo 一致）
    tagsViewStore.delAllViews()
    // 3. 等待DOM更新，确保状态同步
    await nextTick()
    // 4. 跳转登录页（与 UserInfo 一致，携带重定向参数）
    const currentPath = router.currentRoute.value.fullPath
    router.replace({
      path: '/login',
      query: { redirect: currentPath || '/index' }
    })
  } catch (error) {
    console.error('退出登录处理失败:', error)
    // 降级处理：强制刷新到登录页
    window.location.href = '/login'
  }
}

/**
 * 提交表单（核心修复：确保退出逻辑执行）
 */
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 1. 获取公钥
        const hasPublicKey = await fetchPublicKey()
        if (!hasPublicKey) return

        // 2. 加密密码
        const encryptedOldPwd = encryptPassword(password.oldPassword)
        const encryptedNewPwd = encryptPassword(password.newPassword)
        if (!encryptedOldPwd || !encryptedNewPwd) {
          throw new Error('密码加密失败，请重试')
        }

        // 3. 提交修改请求
        await updateUserPassword(encryptedOldPwd, encryptedNewPwd)

        // 4. 提示+退出（直接执行退出，不依赖onClose避免延迟问题）
        message.success('密码修改成功，即将退出登录...')
        // 延迟300ms执行，确保用户看到提示
        setTimeout(async () => {
          await handleLogoutAfterReset()
        }, 300)

      } catch (error) {
        console.error('密码修改失败:', error)
        message.error(error instanceof Error ? error.message : '密码修改失败')
      }
    }
  })
}

/**
 * 重置表单
 */
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 初始化预获取公钥
onMounted(async () => {
  await fetchPublicKey()
})
</script>
